package com.zyb.ext.transaction.transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**
 * 手动实现编程式事务
 */
@Component
@Scope("prototype")     //如果设置为单例的，会出现线程安全问题，多例让每次都获取一个事务对象
public class TransactionUtils {

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;
    //提取事务的状态
    private TransactionStatus transactionStatus;

    //开启事务
    public void begin() {
        //DefaultTransactionAttribute 默认的隔离级别
        transactionStatus = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
    }

    //提交事务
    public void commit() {
        dataSourceTransactionManager.commit(transactionStatus);
    }

    //回滚事务
    public void rollback() {
        dataSourceTransactionManager.rollback(transactionStatus);
    }

    public TransactionStatus getTransactionStatus() {
        return transactionStatus;
    }
}
